import { getDB } from './index.js'

// ============ 广告配置查询 ============

/**
 * 获取广告配置
 * @param {string} platform - 平台类型 (mp-weixin, h5, app-plus)
 * @returns {object|null}
 */
export function getAdConfig(platform = 'mp-weixin') {
  const db = getDB()
  const stmt = db.prepare(`
    SELECT adType, adUnitId, enabled, strategy
    FROM AdConfig
    WHERE platform = ? AND enabled = 1
  `)
  
  const rows = stmt.all(platform)
  
  if (rows.length === 0) {
    return null
  }
  
  const config = {
    banner: '',
    interstitial: '',
    rewardVideo: '',
    native: '',
    enabled: true,
    strategy: {
      browseCount: 5,
      timeInterval: 120000,
      downloadRequireAd: true,
      startupDelay: 5000
    }
  }
  
  rows.forEach(row => {
    config[row.adType] = row.adUnitId
    
    if (row.strategy) {
      try {
        const strategy = JSON.parse(row.strategy)
        config.strategy = { ...config.strategy, ...strategy }
      } catch (e) {
        // 忽略解析错误
      }
    }
  })
  
  return config
}

/**
 * 创建或更新广告配置
 * @param {object} data
 */
export function upsertAdConfig(data) {
  const db = getDB()
  const stmt = db.prepare(`
    INSERT INTO AdConfig (platform, adType, adUnitId, enabled, strategy)
    VALUES (?, ?, ?, ?, ?)
    ON CONFLICT(platform, adType) DO UPDATE SET
      adUnitId = excluded.adUnitId,
      enabled = excluded.enabled,
      strategy = excluded.strategy,
      updatedAt = datetime('now')
  `)
  
  const strategy = data.strategy ? JSON.stringify(data.strategy) : null
  stmt.run(
    data.platform,
    data.adType,
    data.adUnitId,
    data.enabled !== undefined ? data.enabled : 1,
    strategy
  )
}

/**
 * 记录广告事件
 * @param {object} data
 */
export function recordAdEvent(data) {
  const db = getDB()
  const today = new Date().toISOString().split('T')[0]
  
  const stmt = db.prepare(`
    INSERT INTO AdStats (platform, adType, adUnitId, eventType, count, date)
    VALUES (?, ?, ?, ?, 1, ?)
    ON CONFLICT(platform, adType, adUnitId, eventType, date) DO UPDATE SET
      count = count + 1,
      updatedAt = datetime('now')
  `)
  
  stmt.run(
    data.platform || 'mp-weixin',
    data.adType,
    data.adUnitId,
    data.eventType, // show or click
    today
  )
}

/**
 * 获取广告统计
 * @param {object} options
 */
export function getAdStats(options = {}) {
  const db = getDB()
  const { platform, adType, startDate, endDate } = options
  
  let whereClauses = []
  let params = []
  
  if (platform) {
    whereClauses.push('platform = ?')
    params.push(platform)
  }
  if (adType) {
    whereClauses.push('adType = ?')
    params.push(adType)
  }
  if (startDate) {
    whereClauses.push('date >= ?')
    params.push(startDate)
  }
  if (endDate) {
    whereClauses.push('date <= ?')
    params.push(endDate)
  }
  
  const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : ''
  
  const stmt = db.prepare(`
    SELECT platform, adType, adUnitId, eventType, SUM(count) as total, date
    FROM AdStats
    ${whereSql}
    GROUP BY platform, adType, adUnitId, eventType, date
    ORDER BY date DESC
  `)
  
  return stmt.all(...params)
}

// ============ 应用配置查询 ============

/**
 * 获取应用配置
 * @returns {object}
 */
export function getAppConfig() {
  const db = getDB()
  const stmt = db.prepare('SELECT configKey, configValue, description FROM AppConfig')
  const rows = stmt.all()
  
  const config = {
    version: '1.0.0',
    versionCode: 100,
    updateRequired: false,
    updateMessage: '',
    updateUrl: '',
    features: {
      adEnabled: true,
      searchEnabled: true,
      downloadEnabled: true
    },
    recommendations: {
      maxFavorites: 1000,
      maxHistory: 100,
      imageQuality: {
        standard: 'thumbnail',
        hd: 'url',
        original: 'url'
      }
    }
  }
  
  rows.forEach(row => {
    const keys = row.configKey.split('.')
    let obj = config
    
    for (let i = 0; i < keys.length - 1; i++) {
      if (!obj[keys[i]]) {
        obj[keys[i]] = {}
      }
      obj = obj[keys[i]]
    }
    
    const lastKey = keys[keys.length - 1]
    let value = row.configValue
    
    // 尝试转换类型
    if (value === 'true') value = true
    else if (value === 'false') value = false
    else if (!isNaN(value) && value !== '') value = parseInt(value)
    
    obj[lastKey] = value
  })
  
  return config
}

/**
 * 获取所有应用配置项（原始格式）
 * @returns {array}
 */
export function getAllAppConfigs() {
  const db = getDB()
  const stmt = db.prepare('SELECT id, configKey, configValue, description, updatedAt FROM AppConfig ORDER BY configKey')
  return stmt.all()
}

/**
 * 设置应用配置
 * @param {string} key
 * @param {string} value
 * @param {string} description
 */
export function setAppConfig(key, value, description = '') {
  const db = getDB()
  const stmt = db.prepare(`
    INSERT INTO AppConfig (configKey, configValue, description)
    VALUES (?, ?, ?)
    ON CONFLICT(configKey) DO UPDATE SET
      configValue = excluded.configValue,
      description = excluded.description,
      updatedAt = datetime('now')
  `)
  
  stmt.run(key, String(value), description)
}

/**
 * 批量更新应用配置
 * @param {array} configs - [{key, value, description}, ...]
 */
export function batchUpdateAppConfig(configs) {
  const db = getDB()
  const stmt = db.prepare(`
    INSERT INTO AppConfig (configKey, configValue, description)
    VALUES (?, ?, ?)
    ON CONFLICT(configKey) DO UPDATE SET
      configValue = excluded.configValue,
      description = excluded.description,
      updatedAt = datetime('now')
  `)
  
  const transaction = db.transaction((configs) => {
    for (const config of configs) {
      stmt.run(
        config.key,
        String(config.value),
        config.description || ''
      )
    }
  })
  
  transaction(configs)
}

/**
 * 删除应用配置
 * @param {string} key
 */
export function deleteAppConfig(key) {
  const db = getDB()
  const stmt = db.prepare('DELETE FROM AppConfig WHERE configKey = ?')
  stmt.run(key)
}
